<script setup lang="ts">
import { Message } from '@arco-design/web-vue'
import { deleteSwitcherApi, getSwitcherListApi } from '@/apis/modules/switch'
import EditorDialog from './dialogs/EditorDialog.vue'
import useConfig from './useConfig'

const { tableColumns } = useConfig()

const { allRegionOptions } = useRegions()

const queryParams = ref({ region_id: '', name: '' })

const {
  loading,
  data: tableData,
  pagination,
  run,
} = useListRequest(getSwitcherListApi, {
  params: queryParams,
  immediate: true,
})

const {
  visible: editorDialogVisible,
  open: openEditorDialog,
  data: editorDialogData,
} = usePopup()

// 删除交换机
function handleDelete(id: string) {
  ModalHelper.error({
    title: '删除交换机',
    content: '交换机删除后不可恢复，确定要删除该交换机吗？',
    okText: '删除',
    width: 480,
    closable: false,
    onOk: async () => {
      await deleteSwitcherApi({ id })
      await run()
      Message.success('删除成功')
    },
  })
}
</script>

<template>
  <main-container
    v-model:pagination="pagination"
    :loading="loading"
    @run="run"
  >
    <template #header>
      <div class="flex space-x-4">
        <a-button
          type="primary"
          @click="openEditorDialog()"
        >
          新建交换机
        </a-button>
        <a-select
          v-model="queryParams.region_id"
          placeholder="全部区域"
          :options="[{ label: '全部区域', value: '' }, ...allRegionOptions]"
          class="!w-34"
          @change="() => run()"
        />
        <a-input-search
          v-model="queryParams.name"
          placeholder="请输入名称搜索"
          class="!w-58"
          @change="() => run()"
        />
      </div>
    </template>

    <a-table
      v-bind="commonTableProps"
      :columns="tableColumns"
      :data="tableData"
    >
      <template #actions="{ record }">
        <a-link @click="openEditorDialog(record)">
          <i-icons-edit size="16px" />
        </a-link>
        <a-link
          :disabled="record.node_count > 0"
          status="danger"
          @click="handleDelete(record.id)"
        >
          <i-icons-delete size="16px" />
        </a-link>
      </template>
    </a-table>
  </main-container>

  <editor-dialog
    v-model:visible="editorDialogVisible"
    :record="editorDialogData"
    @refresh="run"
  />
</template>

<style scoped></style>
